// packageA/mycomponent/goodsComponent/buyNow/buyNow.js
const app = getApp();
// var level_id = "";
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 详情数据
    goodsInfo: {
      type: null,
    },
    goods_plugin: {
      type: null,
    },
    // 租赁商品
    isRent: {
      type: null,
    },
    //商品id
    goodsId: {
      type: null,
    },
    // 商品类型
    goodsType: {
      type: null,
    },
    mark: {
      type: null,
    },
    mode: {
      type: null
    },
    vieText: {
      type: null,
    },
    fromStock: {
      // 云库存商品
      type: String || Number,
    },
    store_id: {
      // 门店拼团
      type: String || Number,
    },
    coid:{
      type:null
      // 默认规格id
    },
    debtId:{
      type:null
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showSkuImages: false,
    skuImages: false,
    activeSkuIndex: 0,
    activeSkuIndex_1: null, //用于关闭时保存点击预览前的序号，在预览关闭时重新设置预览起始位置
    activeSkuIndex_2: null,
    integral: "积分",
    popupSpecs: false,
    SUBMIT_ACTION_CART: "-1", //添加到购物车
    SUBMIT_ACTION_BUY: "-2", //立即购买
    groupModel: "",
    specsManage: [],
    optionsId: "", //选择后的 规格ID
    goodsCount: 1,
    goodsDescription: "",
    // 库存
    popStock: 0,
    // 价格
    popPrice: 0,
    popThumb: "", // 商品图片
    optionsMaxCount: 1,
    submitActionTag: "-2",
    gooddatas: [],
    activityId: "",
    isAward: "",
    language: "",
    buyType: 0, //新零售购物下单方式，1代理套餐下单，2立即购买
    levelModel: 0,
    give_integral_count:'', //送积分数量
    isMultiSpecs: false, //多规格商品是否显示会员价
    specsVIPPrc: null //规格商品会员价
  },
  observers: {
    "popupSpecs,popupSpecs2,goodsInfo,goodsType": function (popupSpecs,popupSpecs2, Info, type) {
      if (type == "grabGroup") {
        this.setData({
          gooddatas: Info,
        });
      }
      if (popupSpecs) {
        //有规格的弹窗
        console.log("有没有规格id", this.data.optionsId);
        if (!this.data.optionsId) {
          this.firstArr();
        }
      }
    },
  },
  lifetimes: {
    attached() {
      let language = wx.getStorageSync("langIndex");
      let yz_basic_info = wx.getStorageSync('yz_basic_info');
      this.setData({
        language: language.en,
        vip_show:yz_basic_info.globalParameter.vip_show?yz_basic_info.globalParameter.vip_show:false
      });
      const value = wx.getStorageSync("integral");
      if (value) {
        this.setData({
          integral: value,
        });
      }
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    setMrSpec(){
      return new Promise((resolve, reject)=>{
        for(let i = 0;i<this.data.goodsInfo.has_many_options.length;i++){
          if(this.data.goodsInfo.has_many_options[i].id == this.data.coid){
            resolve(this.data.goodsInfo.has_many_options[i].specs);
          }
        }
      });
    },
    async firstArr() {
      let that = this;
      let specsInd;
      if(this.data.coid){
        specsInd = await this.setMrSpec();
        specsInd = specsInd.split("_");
      }
      if (this.data.goodsInfo.has_option == 1){
        for (let i = 0; i < that.data.goodsInfo.has_many_specs.length; i++) {
          if(this.data.coid){
            for(let j = 0;j < this.data.goodsInfo.has_many_specs[i].specitem.length;j++){
              console.log(this.data.goodsInfo.has_many_specs[i].specitem[j].id,Number(this.data.coid),'sssss');
              if(this.data.goodsInfo.has_many_specs[i].specitem[j].id == Number(specsInd[i])){
                this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[j],"first", i);
              }
            }
          }else{
            that.data.goodsInfo.has_many_specs[i].description = that.data.goodsInfo.has_many_specs[i].specitem[0].id;
            that.selectSpecs(that.data.goodsInfo.has_many_specs[i].specitem[0], "first", i);  
          }
        }
      }

      if (this.data.goodsInfo.has_option == 0&&(this.data.goodsType == "group_goods"||this.data.goodsType == "ywmGroup")) {
        this.selectGroup();
      }
    },
    //关闭popupSpecs购买弹窗
    popupSpecsbtn() {
      this.setData({
        popupSpecs: false,
        popupModeshow: true,
      });
      this.triggerEvent("popupModeshowChild", true);
      this.triggerEvent('paramsOptionsId',{'option':this.data.optionsId,'goodsCount':this.data.goodsCount});
    },
    getOptionsMaxCount(num) {
      let goods_plugin = this.data.goods_plugin;
      if (goods_plugin && goods_plugin.month_buy_limit && goods_plugin.month_buy_limit != [] && goods_plugin.month_buy_limit.hasOwnProperty('limit')) {
        let { limit, member_purchased } = goods_plugin.month_buy_limit;
        // 海诚-商品分类会员等级限购#89586
        let max = Number(limit) - Number(member_purchased);
        return max > 0 ? max : 1;
      } else {
        return num;
      }
    },
    // 增加数量
    addGoods() {
      if (this.data.goodsType == "grabGroup" ) {
        return;
      }
      let lastgoodsCount = this.data.goodsCount;
      let specsManage = this.data.specsManage;
      let optionsMaxCount =  this.getOptionsMaxCount(this.data.goodsInfo.stock);
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length && this.data.goodsCount == optionsMaxCount) {
        wx.showToast({
          icon: "none",
          title: `最多购买${optionsMaxCount}件`,
          duration: 2500,
        });
        console.log("max=" + this.data.goodsCount);
        return;
      }
      this.setData({
        goodsCount: Number(lastgoodsCount) + 1,
      });
    },
    // 减少数量
    reduceGoods() {
      if (this.data.goodsType == "grabGroup") {
        return;
      }
      let lastgoodsCount = this.data.goodsCount;
      if (this.data.goodsCount == 1 || this.data.goodsCount == 0) {
        return;
      }
      this.setData({
        goodsCount: lastgoodsCount - 1,
      });
    },
    //============ 处理规格图片点击放大 start============
    showSkuImages_Methob() {
      // this.triggerEvent('popupModeshowChild', true) 传给父组件取消遮罩
      this.triggerEvent("popupModeshowChild", true);
      console.log(this.data.skuImages);
      this.setData({
        popupSpecs: false,
        popupSpecs2: false,
        // popupModeshow: true,
        showSkuImages: true,
      });
      if (this.data.goodsInfo.has_option != 1) {
        return;
      }
      this.setData({
        activeSkuIndex_1: this.data.goodsInfo.has_many_options[this.data.activeSkuIndex].specs,
      });
    },
    // 图片滑动事件
    onChangeSkuImagesIndex(e) {
      let _index = e.detail.current;
      this.setData({
        activeSkuIndex: _index,
      });
      if (this.data.goodsInfo.has_option != 1) {
        return;
      }
      this.setData({
        activeSkuIndex_2: this.data.goodsInfo.has_many_options[_index].specs,
      });
    },
    // 关闭浏览图片
    onCloseSkuImages() {
      console.log(this.data.goodsInfo);
      if (this.data.goodsInfo.has_option != 1) {
        this.setData({
          popupSpecs2: true,
          popupModeshow: false,
          showSkuImages: false,
        });
        this.triggerEvent("popupModeshowChild", false);
        return;
      }
      let _lastOption = this.data.activeSkuIndex_1.split("_");
      let goodsInfo = this.data.goodsInfo;
      let _activeSkuIndex = this.data.activeSkuIndex;

      if (this.data.activeSkuIndex_1 != this.data.goodsInfo.has_many_options[_activeSkuIndex].specs) {
        let _activeOption = this.data.activeSkuIndex_2.split("_"); //如果没有滑动直接取值是取不到报错的
        for (let i = 0; i < _lastOption.length; i++) {
          if (_lastOption[i] != _activeOption[i]) {
            let _specs = Number(_activeOption[i]);
            for (let ind = 0; ind < this.data.goodsInfo.has_many_specs.length; ind++) {
              for (let index = 0; index < this.data.goodsInfo.has_many_specs[ind].specitem.length; index++) {
                if (this.data.goodsInfo.has_many_specs[ind].specitem[index].id == _specs) {
                  goodsInfo.has_many_specs[ind].description = this.data.goodsInfo.has_many_specs[ind].specitem[index].id;
                  // this.selectSpecs(this.data.goodsInfo.has_many_specs[ind].specitem[index],"sku_swiper")
                }
              }
            }
          }
        }
      }

      let popPrice = "";
      if (this.data.goods_plugin.point_goods) {
        popPrice = this.data.goods_plugin.point_goods.point_option[_activeSkuIndex].goods_point; //设置默认价格
      } else {
        popPrice = this.data.goodsInfo.has_many_options[_activeSkuIndex].product_price; //设置默认价格
      }
      this.triggerEvent("popupModeshowChild", false);
      this.setData({
        goodsInfo: goodsInfo,
        showSkuImages: false,
        popupSpecs: true,
        popupModeshow: false,
        popPrice: popPrice, //设置价格
        popThumb: app._isTextEmpty(this.data.goodsInfo.has_many_options[_activeSkuIndex].thumb) ? this.data.goodsInfo.thumb : this.data.goodsInfo.has_many_options[_activeSkuIndex].thumb, //设置图片
        popStock: this.data.goodsInfo.has_many_options[_activeSkuIndex].stock, //设置库存
        optionsId: this.data.goodsInfo.has_many_options[_activeSkuIndex].id, //设置规格ID，用于生成订单
      });
    },
    //============ 处理规格图片点击放大 end============
    //初始化弹窗view
    initPopView() {
      let popPrice = "";
      if (this.data.goodsInfo.has_option == 1) {
        if (this.data.goods_plugin.point_goods) {
          popPrice = this.data.goods_plugin.point_goods.min_point + "-" + this.data.goods_plugin.point_goods.max_point; //设置默认价格
        } else {
          popPrice = this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price; //设置默认价格
        }
        this.setData({
          popPrice: popPrice, //设置默认价格
          popThumb: this.data.goodsInfo.thumb, //设置默认图片
          popStock: this.data.goodsInfo.stock, //设置默认库存
          goodsDescription: "选择",
        });
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          this.setData({
            goodsDescription: this.data.goodsDescription + " " + this.data.goodsInfo.has_many_specs[i].title,
          });
        }
        let _optionArr = [];
        this.data.goodsInfo.has_many_options.forEach((val, index) => {
          let _thumb = val.thumb != "" ? val.thumb : this.data.goodsInfo.thumb;
          _optionArr.push(_thumb);
        });
        this.setData({
          skuImages: _optionArr,
        });
      } else {
        let __optionArr2 = [];
        __optionArr2.push(this.data.goodsInfo.thumb);

        if (this.data.goods_plugin.point_goods) {
          popPrice = this.data.goods_plugin.point_goods.point; //设置默认价格
        } else {
          popPrice = this.data.goodsInfo.price; //设置默认价格
        }
        this.setData({
          popThumb: this.data.goodsInfo.thumb, //设置默认图片
          popStock: this.data.goodsInfo.stock, //设置默认库存
          popPrice: popPrice, //设置默认价格
          goodsDescription: "",
          optionsMaxCount: this.data.goodsInfo.stock,
          skuImages: __optionArr2,
        });
      }
    },
    //新处理立即购买
    buyNowNew() {
      if(this.data.submitActionTag == this.data.SUBMIT_ACTION_CART){
        //购物车网络处理
        this.setData({
          popupSpecs: false,
        });
        this.triggerEvent("popupModeshowChild", true);
        this.addCartRequest(this.data.goodsId, this.data.optionsId, this.data.goodsCount);
        this.hidePopView2();
        return;
      }
      this.hidePopView2();
      //处理参数
      // console.log(this.data.goodsId, this.data.optionsId, this.data.goodsCount);
      // console.log(this.data.goodsType);
      if (this.data.goodsType == "retailGood") {
        this.buyNowRequestRetailGood(this.data.goodsId, this.data.optionsId, this.data.goodsCount);
      } else if (this.data.goodsType == "zhpGroup") {
        this.buyNowRequestZhpGroup(this.data.goodsId, this.data.optionsId, this.data.goodsCount);
      } else {
        this.buyNowRequest(this.data.goodsId, this.data.optionsId, this.data.goodsCount);
      }
    },
    hidePopView2() {
      // this.triggerEvent('popupModeshowChild', true) 传给父组件取消遮罩
      this.triggerEvent("popupModeshowChild", true);
      this.setData({
        popupSpecs2: false,
      });
    },
    //立即购买网络操作  no
    buyNowRequest(_goodsId, _optionsId, _total) {
      //库存不足
      if (this.data.optionsMaxCount == 0) {
        wx.showToast({
          icon: "none",
          title: "商品库存不足",
          duration: 2500,
        });
        return;
      }
      if (_total <= 0) {
        wx.showToast({
          icon: "none",
          title: "请选择商品数量",
          duration: 2500,
        });
        return;
      }
      if (this.data.goodsInfo.has_option == 1 && app._isTextEmpty(_optionsId)) {
        wx.showToast({
          icon: "none",
          title: "请选择规格！",
          duration: 2500,
        });
        return;
      }
      let that = this;
      let goods = [];
      goods.push(_goodsId);
      let urlStr = app.getNetAddresss("from.div-from.isDisplay");
      urlStr += "&goods_ids=" + JSON.stringify(goods);
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            // var _data = res.data;
            if (res.data.status && !res.data.member_status) {
              wx.showModal({
                title: "提示",
                content: "购买此商品,请补充您的个人信息",
                success(res) {
                  if (res.confirm) {
                    //保税真实信息添加
                    wx.navigateTo({
                      url: "/packageB/member/address/myinfo/myinfo?tag=delta",
                    });
                  } else if (res.cancel) {
                    console.log("用户点击取消");
                  }
                },
              });
            } else {
              let url = "/packageD/buy/myOrder_v2/myOrder_v2?goodsId=" + _goodsId + "&optionsId=" + _optionsId + "&total=" + _total + '&tag=';
              if (that.data.activityid) {
                wx.navigateTo({
                  url: url + that.data.submitActionTag + "&activity_id=" + that.data.activityid,
                });
                return;
              }
              if(!app._isTextEmpty(that.data.debtId)){
                // 有债务人店铺id就加上
                wx.navigateTo({
                  url: url + "&debtId=" + that.data.debtId,
                });
                return;
              }
              if (that.data.goodsType == "appointment_goods") {
                wx.navigateTo({
                  url: url + "appointment_goods",
                });
                return;
              }
              if (that.data.goodsType == "yunqian_api") {
                wx.navigateTo({
                  url: url + "yunqian_api",
                });
                return;
              }
              if (that.data.goodsType == "store_projects_goods") {
                //* 门店核销
                wx.navigateTo({
                  url: url + "store_projects_goods",
                });
                return;
              }
              if(that.data.mark == 'vending_machine'){   //自动售货机
                wx.navigateTo({
                  url: url + "machine" + '&machineId='+that.data.goods_plugin.automat.machine_id,
                });
                return;
              }
              if (!that.data.isCup) {
                if (that.data.isRent) {
                  console.log(that.data.goods_plugin,'goods_plugin')
                  console.log(that.data.isRent,'dddddddddddddd')
                  if(that.data.goods_plugin.yz_supply_lease.is_yz_supply_lease){
                    wx.navigateTo({
                      url: url + "yzlease"
                    });
                    return
                  }
                  wx.navigateTo({
                    url: url + "rentBuy" + "&mark=" + that.data.mark,
                  });
                } else {
                  url = url + that.data.submitActionTag + "&mark=" + that.data.mark + "&fromStock=" + that.data.fromStock;
                  wx.navigateTo({
                    url: url,
                  });
                }
              } else if (that.data.vieText == "POrder") {
                wx.navigateTo({
                  url: url + "POrder",
                });
              } else {
                wx.navigateTo({
                  url: url + that.data.submitActionTag + "&fromStock=" + that.data.fromStock,
                });
              }
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
        fail: function (res) {},
      });
    },
    //提交确认
    submitAction() {
      let specsManage = this.data.specsManage;
      if (specsManage.length < this.data.goodsInfo.has_many_specs.length) {
        this.setData({
          popupSpecs: false,
        });
        this.triggerEvent("popupModeshowChild", true);
        wx.showToast({
          icon: "none",
          title: this.data.goodsDescription,
          duration: 2500,
        });
        return;
      }
      if (this.data.submitActionTag == this.data.SUBMIT_ACTION_CART) {
        //购物车网络处理
        this.setData({
          popupSpecs: false,
        });
        this.triggerEvent("popupModeshowChild", true);
        this.addCartRequest(this.data.goodsId, this.data.optionsId, this.data.goodsCount);
      } else if (this.data.submitActionTag == this.data.SUBMIT_ACTION_BUY) {
        //立即购买处理
        this.setData({
          popupSpecs: false,
        });
        this.triggerEvent("popupModeshowChild", true);
        if(this.data.submitTag == 'design'){
          this.triggerEvent('paramsOptionsId',{'option':this.data.optionsId,'goodsCount':this.data.goodsCount});
          return;
        }
        this.buyNowRequest(this.data.goodsId, this.data.optionsId, this.data.goodsCount);
      }
    },
    // 输入数量
    inputGoodsNum: function (e) {
      var num = parseInt(e.detail.value);
      var lastgoodsCount = this.data.goodsCount;
      if (e.detail.keyCode == 8) {
        if (app._isTextEmpty(e.detail.value)) {
          this.setData({
            goodsCount: "",
          });
          return;
        }
      }
      if (num) {
        this.setData({
          goodsCount: num,
        });
      } else {
        this.setData({
          goodsCount: lastgoodsCount,
        });
      }
    },
    //============================= 规格操作处理 ==============================
    //界面选择规格触发事件
    selectSpecs(e, str, i) {
      let data = {};
      let specsIdex = 0;
      if (str == "first") {
        specsIdex = i;
        data = e;
      } else if (str == "sku_swiper") {
        data = e;
      } else {
        specsIdex = e.currentTarget.dataset.specsidex;
        data = e.currentTarget.dataset.specitem;
      }

      if (data.c) {
        return false;
      }
      this.setData({
        ["goodsInfo.has_many_specs[" + specsIdex + "].description"]: data.id,
      });
      this.isShowMultiSpecsMemPrice(); //是否需要显示多规格会员价
      // let specid = data.specid; //对其他数据筛选 不筛选同级
      //处理选择池
      this.manageSpecs(data);
      //处理规格组合选择状态
      this.setGoodsSpecs(data);
      //设置选择规格后的 价格、照片、库存
      this.setGoodsSpecsChangeInfo();
      //判断当前购买总量与库存的关系
      if(this.data.goodsInfo.min_buy_num){
        this.setData({
          goodsCount:this.data.goodsInfo.min_buy_num,
        })
      }
      this.getMaxCount();
      this.triggerEvent('paramsOptionsId',{'option':this.data.optionsId,'goodsCount':this.data.goodsCount});
    },
    isShowMultiSpecsMemPrice() {
      //判断是否需要显示多规格会员价【#70785】
      let arr = ["groupBuy", "grabGroup", "grabGroup", "group_goods",'retailGood','starGroup','zhpGroup','ywmGroup']; //拼团类（独立的金额设置没有关联商城商品规格价）、积分商品不需要显示会员价
      if (arr.indexOf(this.data.goodsType) != -1) {
        this.setData({
          isMultiSpecs: false
        });
        return;
      }
      this.setData({
        isMultiSpecs: this.data.vip_show
      });
      //注释代码 this.goodsInfo.is_open_micro && Number(this.goodsInfo.is_open_micro) == 1
      //注释原因：二开会员价 #87399 去掉原插件判断
      // let _is_open_micro = 0;
      // if (this.data.goods_plugin) _is_open_micro = this.data.goods_plugin?.member_price?.is_open_micro || 0;
      // if (Number(_is_open_micro) == 1 && this.data.goodsInfo.has_option == 1) {
      //   this.setData({
      //     isMultiSpecs: true
      //   });
      // } else {
      //   this.setData({
      //     isMultiSpecs: false
      //   });
      // }
    },
    //处理选择池
    manageSpecs(data) {
      let specsObject = new Object();
      let specsManage = this.data.specsManage;
      specsObject.id = data.id;
      specsObject.specid = data.specid;
      specsObject.title = data.title;

      if (specsManage.length > 0) {
        for (let i = 0; i < specsManage.length; i++) {
          if (specsManage[i].specid == specsObject.specid) {
            specsManage.splice(i, 1);
          }
        }
        specsManage.push(specsObject);
      } else {
        specsManage.push(specsObject);
      }

      //排序
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        var newSpecsManage = [];
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.data.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
              newSpecsManage.push(specsManage[j]);
              break;
            }
          }
        }
        specsManage = newSpecsManage;
      }
      this.setData({
        specsManage: specsManage,
      });
      this.setGoodsDescription();
    },
    //处理goodsDescription 数据
    setGoodsDescription() {
      let description = "";
      let specsManage = this.data.specsManage;
      //相等代表全选了 体现语句
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        description = "已选择 ";
        for (let i = 0; i < specsManage.length; i++) {
          description += specsManage[i].title + " ";
        }
        this.setData({
          goodsDescription: description,
        });
      } else {
        description = "请选择 ";
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.data.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
              description += this.data.goodsInfo.has_many_specs[i].title + " ";
              break;
            }
          }
        }
        this.setData({
          goodsDescription: description,
        });
      }
    },
    //处理规格组合选择状态 过滤数据
    setGoodsSpecs(specs) {
      // let goodsInfo = this.data.goodsInfo;
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        if (specs.specid != this.data.goodsInfo.has_many_specs[i].id) {
          // let specitem = this.setGoodsSpecsStatus(this.data.goodsInfo.has_many_specs[i].specitem, specs.id);
          // this.setData({
          // 	["goodsInfo.has_many_specs[" + i + "].specitem"]: specitem
          // })
        }
      }
    },
    //设置选择规格后的 价格、照片、库存
    setGoodsSpecsChangeInfo() {
      let specsManage = this.data.specsManage;
      let popPrice = "";
      //根据ID 排序 specsManage.sort();
      specsManage.sort(function (a, b) {
        return a.id - b.id;
      });
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"
        for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
          if (goodsSpecs == this.setGoodsSpecsBySort(this.data.goodsInfo.has_many_options[i].specs)) {
            if (this.data.goods_plugin.point_goods) {
              popPrice = this.data.goods_plugin.point_goods.point_option[i].goods_point; //设置默认价格
            } else {
              popPrice = this.data.goodsInfo.has_many_options[i].product_price; //设置默认价格
            }
            this.setData({
              activeSkuIndex: i,
              popPrice: popPrice, //设置价格
              popThumb: app._isTextEmpty(this.data.goodsInfo.has_many_options[i].thumb) ? this.data.goodsInfo.thumb : this.data.goodsInfo.has_many_options[i].thumb, //设置图片
              popStock: this.data.goodsInfo.has_many_options[i].stock, //设置库存
              optionsId: this.data.goodsInfo.has_many_options[i].id, //设置规格ID，用于生成订单
              give_integral_count:this.data.goodsInfo.has_many_options[i].points
            });
            this.data.optionsMaxCount = this.data.goodsInfo.has_many_options[i].stock; //库存最大数 用于切换更改买家购买数量
            if (this.data.optionsMaxCount > 0) {
              this.setData({
                goodsCount: 1,
              });
            }
            if (this.data.isMultiSpecs) this.getMemberPrice(this.data.optionsId);

            if (this.data.goodsType == "group_goods"||this.data.goodsType == "ywmGroup") {
              console.log(this.data.goodsType, 'group_goods');
              this.setGroupInfo(this.data.optionsId); // 设置选择后规格对应的层级 过滤数据
            } else {
              this.setZhpGroupInfo(this.data.optionsId);
            }
            break;
          }
        }
      }

      this.setData({
        specsManage: specsManage,
      });
    },
    //处理商品goodsSpecs 并排序 新方法
    setGoodsSpecsBySort(specs) {
      let _specs = specs.split("_"); //先变成数组
      //_specs.sort();//排序
      _specs.sort(function (a, b) {
        return a - b;
      });
      // 在组装回去
      let goodsSpecs = "";
      for (let j = 0; j < _specs.length; j++) {
        goodsSpecs += _specs[j] + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"
      return goodsSpecs;
    },
    //判断当前购买总量与库存的关系
    getMaxCount() {
      let specsManage = this.data.specsManage;
      let optionsMaxCount = this.data.optionsMaxCount;
      if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
        if (optionsMaxCount == 0) {
          //库存不足
          this.setData({
            goodsCount: 0,
          });
        }
        if (this.data.goodsCount > optionsMaxCount) {
          this.setData({
            goodsCount: optionsMaxCount,
          });
        }
      }
    },
    // ================================= end ============================
    getMemberPrice(_optionsId) {
      if (!_optionsId) return;
      let specsVIPPrc = 0;
      this.setData({specsVIPPrc});
      let urlStr = app.getNetAddresss("goods.other-info.option-vpi-price");
      urlStr += "&option_id=" + _optionsId;
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          let res = resdata.data;
          if (res.result == 1) {
            specsVIPPrc = res.data.vip_price || null;
          } else {
            specsVIPPrc = null;
          }
          this.setData({specsVIPPrc});
        },
        fail: function (res) {
          specsVIPPrc = null;
          this.setData({specsVIPPrc});
        },
      });
      
    },
    //******************** 加入购物车网络操作 ***************
    addCartRequest(_goodsId, _optionsId, _total) {
      //库存不足
      if (this.data.optionsMaxCount == 0) {
        wx.showToast({
          icon: "none",
          title: "商品库存不足",
          duration: 2500,
        });
        return;
      }
      if (_total <= 0) {
        this.setData({
          popupSpecs: false,
          popupModeshow: true,
        });
        wx.showToast({
          icon: "none",
          title: "请选择商品数量",
          duration: 2500,
        });
        return;
      }

      let that = this;
      let goods = [];
      goods.push(_goodsId);
      let urlStr = app.getNetAddresss("from.div-from.isDisplay");
      urlStr += "&goods_ids=" + JSON.stringify(goods);
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            // var _data = res.data;
            if (res.data.status && !res.data.member_status) {
              wx.showModal({
                title: "提示",
                content: "购买此商品,请补充您的个人信息",
                success(res) {
                  if (res.confirm) {
                    //保税真实信息添加
                    wx.navigateTo({
                      url: "/packageB/member/address/myinfo/myinfo?tag=delta",
                    });
                  } else if (res.cancel) {
                    console.log("用户点击取消");
                  }
                },
              });
            } else {
              that.addCartReq(_goodsId, _optionsId, _total);
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
        fail: function (res) {},
      });
    },
    addCartReq(_goodsId, _optionsId, _total) {
      // let that = this;
      let urlStr = app.getNetAddresss("member.member-cart.store");
      urlStr += "&goods_id=" + _goodsId;
      urlStr += "&total=" + _total;
      urlStr += "&option_id=" + _optionsId;
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            app.globalData.cart_num = res.data.cart_num;
            this.triggerEvent('changeCartNumber', res.data.cart_num);
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          } else {
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              success (res) {}
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    // *********************** 加入购物车网络操作end ****************
    // *********************** 拼团  Start ****************
    selectGroup(e) {
      if (e) {
        let item = e.target.dataset.item || e.currentTarget.dataset.item;
        this.setData({
          groupModel: item.id
        });
      }
      if(!this.data.groupModel){
        this.setData({
          groupModel: this.data.gooddatas.has_many_level[0].id
        });
      }
      let selectGroupLever = [];
      if (!app._isTextEmpty(this.data.groupModel)) {
        if (this.data.goodsInfo.has_option == 1) {
          // 有规格
          if (app._isTextEmpty(this.data.optionsId) || this.data.optionsId == 0) {
            wx.showToast({
              title: "请选择商品规格！",
              icon: "none",
              duration:2500
            });
            this.setData({
              groupModel: "",
            });
            return;
          } else {
            selectGroupLever = this.data.selectGroupInfo.filter( (v)=> {
              if (v.level_id == this.data.groupModel) {
                return v.group_price;
              }
            });
            this.setData({
              popPrice: selectGroupLever[0].group_price,
            });
            this.setData({
              option_level_id: selectGroupLever[0].id,
            });
          }
        } else {
          // 无规格
          this.setData({
            selectGroupInfo: this.data.gooddatas.has_many_options[0].has_many_option_level,
            optionsMaxCount: this.data.gooddatas.has_many_options[0].buy_limit == 0 ? this.data.gooddatas.has_many_options[0].stock : this.data.gooddatas.has_many_options[0].buy_limit // 当前组合的购买限制数, 为0 时为无限制购买
          });

          selectGroupLever = this.data.selectGroupInfo.filter( (v)=> {
            if (v.level_id == this.data.groupModel) {
              return v.group_price;
            }
          });
          this.setData({
            option_level_id: selectGroupLever[0].id,
            popPrice: selectGroupLever[0].group_price,
          });
        }
      }
    },
    openCardGroup(){
      // 开团卡开团
      let that = this;
      wx.showModal({
        title: '提示',
        content: '确认开团',
        success (res) {
          if (res.confirm) {
            that.confirmOpenCardGroup();
          } else if (res.cancel) {
            that.setData({
              popupSpecs:false,
              popupSpecs2:false
            })
          }
        }
      })
    },
    confirmOpenCardGroup(){
      let _json = {
        member_open_group_id: this.data.gooddatas.member_open_card_id,
        group_id: this.data.gooddatas.id,
        goods: JSON.stringify([{
          goods_id: this.data.goodsId,
          option_id: this.data.optionsId,
          total: 1,
        }]),
        level_id: this.data.groupModel,
        option_level_id: this.data.option_level_id
      };

      let urlStr = app.getNetAddresss("plugin.ywm-fight-groups.frontend.controllers.fight-groups.card-open-group");
      app._postNetWork({
        url: urlStr,
        data: _json,
        success: (resdata) => {
          let res = resdata.data;
          app.tips(res.msg);
          if (res.result == 1) {
            this.setData({
              popupSpecs:false,
              popupSpecs2:false
            })
            this.triggerEvent("popupModeshowChild", true);
            wx.redirectTo({url: '/packageB/member/group/ywmGroupsMyGroups/ywmGroupsMyGroups'})
          }
        }
      });
    },
    openTeam() {
      let that = this;
      // popStock
      if (this.data.popStock == 0||this.data.goodsCount > this.data.popStock) {
        wx.showToast({
          title: "库存不足",
          icon: "none",
          duration:2500
        });
        this.setData({
          goodsCount: this.data.popStock,
        });
        return;
      }
      if (this.data.optionsMaxCount != 0 && this.data.goodsCount > this.data.optionsMaxCount) {
        wx.showToast({
          title: `抱歉，该商品限购${this.data.optionsMaxCount}件`,
          icon: "none",
          duration:2500
        });
        this.setData({
          goodsCount: this.data.optionsMaxCount,
        });
        return;
      }
      if (this.data.goodsCount < 0) {
        wx.showToast({
          title: "商品数量不能小于0",
          icon: "none",
          duration:2500
        });
        this.setData({
          goodsCount: 1,
        });
        return;
      }

      if (app._isTextEmpty(this.data.groupModel)) {
        wx.showToast({
          title: "请选择开团点",
          icon: "none",
          duration:2500
        });
        return;
      }
      let goods = [];
      goods.push(that.data.goodsId);
      let urlStr = app.getNetAddresss("from.div-from.isDisplay");
      urlStr += "&goods_ids=" + JSON.stringify(goods);
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            var _data = res.data;
            console.log("xxxx", _data);
            if (res.data.status && !res.data.member_status) {
              wx.showModal({
                title: "提示",
                content: "购买此商品,请补充您的个人信息",
                success(res) {
                  if (res.confirm) {
                    //保税真实信息添加
                    wx.navigateTo({
                      url: "/packageB/member/address/myinfo/myinfo?tag=group" + "&activityId=" + that.data.activityId,
                    });
                    that.triggerEvent("popupModeshowChild", true);
                    that.setData({
                      popupSpecs:false,
                      popupSpecs2:false
                    })
                  } else if (res.cancel) {
                    console.log("用户点击取消");
                  }
                },
              });
            } else {
              let storeid = 0;
              if (that.properties.store_id && that.properties.store_id != undefined && that.properties.store_id != 0) {
                storeid = that.properties.store_id;
              }
              let URL = "/packageD/buy/myOrder_v2/myOrder_v2?tag=-2" +
              "&goodsId=" +
              that.data.goodsId +
              "&optionsId=" +
              that.data.optionsId +
              "&total=" +
              that.data.goodsCount +
              "&level_id=" +
              that.data.groupModel +
              "&option_level_id=" +
              that.data.option_level_id

              if(storeid) URL = URL + "&groupStoreID=" + storeid;
              if(that.data.goodsType == 'ywmGroup') URL = URL + '&plu=ywm'

              wx.navigateTo({
                url: URL
              });
              that.triggerEvent("popupModeshowChild", true);
              that.setData({
                popupSpecs:false,
                popupSpecs2:false
              })
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
        fail: function (res) {},
      });
    },
    // 设置拼团层级的选择状态 过滤数据
    setGroupInfo(_id) {
      let that = this;
      if(this.data.gooddatas && this.data.gooddatas.has_many_options){
        for (let i = 0; i < this.data.gooddatas.has_many_options.length; i++) {
          let _optionSpecs = this.data.gooddatas.has_many_options[i].option_id;
          if (_optionSpecs == this.data.optionsId) {
            that.setData({
              selectGroupInfo: this.data.gooddatas.has_many_options[i].has_many_option_level,
            });
            this.data.optionsMaxCount = this.data.gooddatas.has_many_options[i].buy_limit == 0 ? this.data.gooddatas.has_many_options[0].stock : this.data.gooddatas.has_many_options[0].buy_limit; // 当前组合的购买限制数, 为0 时为无限制购买
            this.setData({
              popStock:this.data.gooddatas.has_many_options[i].stock,
            });

            this.selectGroup();
            return;
          }
        }
      }
    },
    // 抢团
    checkActivity() {
      let that = this;
      let urlStr = null;
      if (this.data.popPrice == 0) {
        wx.showModal({
          title: "提示",
          showCancel: false,
          content: "开团/参团金额不正确，不能为0",
          success(res) {},
        });
        return;
      }
      urlStr = app.getNetAddresss("plugin.snatch-regiment.api.index.getSnatchData");
      urlStr += "&at_id=" + this.data.activityId + "&art=inspectOverrun" + "&option_id=" + this.data.optionsId + "&goods_id=" + this.data.goodsId + "&total=" + this.data.goodsCount;
      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            this.setData({
              isCheckActivity: true,
            });
            console.log(this.data.isAward, "456");
            if (this.data.goodsType == "grabGroup" && this.data.isAward == 1) {
              console.log("团长开团不参与中奖");
              //团长开团不参与中奖
              wx.showModal({
                title: "提示",
                content: "开团后不参与中奖？",
                success(res) {
                  if (res.confirm) {
                    that.popupSpecsbtn();
                    that.OpenLeader();
                  } else if (res.cancel) {
                    wx.showToast({
                      icon: "none",
                      title: "已取消",
                      duration: 2500,
                    });
                  }
                },
              });
            } else if (this.data.goodsType == "grabGroup" && this.data.isAward == 2) {
              //团长开团参与中奖
              this.submitActionQt();
            }
          } else {
            this.setData({
              isCheckActivity: false,
            });
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
      });
    },
    OpenLeader() {
      let that = this;
      let urlStr = app.getNetAddresss("plugin.snatch-regiment.api.team.OpenLeader");
      urlStr += "&at_id=" + that.data.activityId + "&goods_id=" + that.data.goodsId;

      app._getNetWork({
        url: urlStr,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showToast({
              icon: "none",
              title: "开团成功!",
              duration: 2500,
            });
            wx.navigateTo({
              url: "/packageE/grab_group/grab_group_my/grab_group_my",
            });
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
      });
    },
    submitActionQt() {
      let _goodsId = this.data.goodsId;
      let _optionsId = this.data.optionsId;
      let _total = this.data.goodsCount;
      //库存不足
      if (this.data.optionsMaxCount == 0) {
        wx.showToast({
          icon: "none",
          title: "商品库存不足",
          duration: 2500,
        });
        return;
      }
      if (_total <= 0) {
        wx.showToast({
          icon: "none",
          title: "请选择商品数量",
          duration: 2500,
        });
        return;
      }
      let that = this;
      let goods = [];
      goods.push(_goodsId);
      let urlStr = app.getNetAddresss("from.div-from.isDisplay");
      urlStr += "&goods_ids=" + JSON.stringify(goods);
      app._getNetWork({
        showToastIn: false,
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            // var _data = res.data;
            if (res.data.status && !res.data.member_status) {
              wx.showModal({
                title: "提示",
                content: "购买此商品,请补充您的个人信息",
                success(res) {
                  if (res.confirm) {
                    //保税真实信息添加
                    wx.navigateTo({
                      url: "/packageB/member/address/myinfo/myinfo?tag=delta",
                    });
                  } else if (res.cancel) {
                    console.log("用户点击取消");
                  }
                },
              });
            } else {
              wx.navigateTo({
                url: "/packageD/buy/myOrder_v2/myOrder_v2?tag=-2" + "&optionsId=" + _optionsId + "&goodsId=" + _goodsId + "&total=" + _total + "&type=grabGroup_open" + "&at_id=" + that.data.activityId,
              });
            }
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 2500,
            });
          }
        },
        fail: function (res) {},
      });
    },
    //  ==================================    新零售  ---  购买流程   ============================
    buyNowRequestRetailGood(_goodsId, _optionsId, _total) {
      if (this.data.optionsMaxCount == 0) {
        wx.showToast({
          icon: "none",
          title: "商品库存不足",
          duration: 2500,
        });
        return;
      }
      if (_total <= 0) {
        wx.showToast({
          icon: "none",
          title: "请选择商品数量",
          duration: 2500,
        });
        return;
      }
      if (this.data.goodsInfo.has_option == 1 && app._isTextEmpty(_optionsId)) {
        wx.showToast({
          icon: "none",
          title: "请选择规格！",
          duration: 2500,
        });
        return;
      }

      if (this.data.popPrice == 0) {
        wx.showToast({
          icon: "none",
          title: "价格设置有误，请联系客服！",
          duration: 2500,
        });
        return;
      }
      if (this.data.mode == 2 && this.data.levelModel == 0) {
        wx.showToast({
          icon: "none",
          title: "请选择等级套餐！",
          duration: 2500,
        });
        return;
      }

      let url = "/packageD/buy/myOrder_v2/myOrder_v2?tag=newRetail";
      //自主进货下单：相当于不需要配送方式的虚拟商品
      //retail_state: 0-自由零售 1-成为代理商订单 2-自由发货 3-线上零售 4-进货订单 5-销售代理套餐订单
      let retail_state = null;
      console.log(this.data.buyType, "asdasd");
      if (this.data.mode == 3 && this.data.buyType == 2) {
        //自由进货
        retail_state = 4;
      } else if (this.data.mode == 2 && this.data.buyType == 2) {
        //代理套餐 的 立即购买
        retail_state = 1;
        wx.navigateTo({
          url: url + "&goodsId=" + _goodsId + "&optionsId=" + _optionsId + "&total=" + _total + "&retailState=" + retail_state + "&NRLevelId=" + this.data.levelModel,
        });
        return;
      } else if (this.data.mode == 1 && this.data.buyType == 2) {
        //自由零售
        retail_state = 0;
      } else if (this.data.mode == 2 && this.data.buyType == 1) {
        //代理套餐 的代理销售。跳转二维码页面
        retail_state = 5;
        this.agentSales(_optionsId, _total);
        return;
      }

      wx.navigateTo({
        url: url + "&goodsId=" + _goodsId + "&optionsId=" + _optionsId + "&total=" + _total + "&retailState=" + retail_state,
      });
    },
    agentSales(_optionsId, goodsCount) {
      // let that = this;
      let urlStr = app.getNetAddresss("plugin.new-retail.frontend.index.agentSales");
      app._postNetWork({
        url: urlStr,
        data: {
          goods_id: this.data.goodsId,
          goods_option: _optionsId,
          goods_num: goodsCount,
          level_id: this.data.levelModel,
          goods_name: this.data.goodsInfo.title,
        },
        success: (resdata) => {
          let res = resdata.data;
          this.popupSpecsbtn();
          if (res.result == 1) {
            wx.navigateTo({
              url: "/packageH/newRetail/newRetail_agencyPackage/newRetail_agencyPackage?id=" + res.data.id,
            });
          } else {
            wx.showToast({
              title: res.msg,
              duration: 2500,
              icon: "none",
            });
          }
        },
        fail: function (res) {
          wx.hideLoading();
          console.log(res.msg);
        },
      });
    },
    clickLevelModel(e) {
      let item = e.currentTarget.dataset.item;
      this.setData({
        popPrice: item.level_unit_total_price,
        goodsCount: item.level_num,
        levelModel: item.level_id,
      });
    },
    //  --------------------------------------------  珍惠拼 拼团 -----------------------------------------------------
    buyNowRequestZhpGroup(_goodsId, _optionsId, _total) {
      this.hidePopView2();
      let submitActionTag = 'zhpGroup';
      let activity_id = this.data.gooddatas.id;
      let url = "/packageD/buy/myOrder_v2/myOrder_v2?tag=";
      this.triggerEvent("popupModeshowChild", true);
      if (_optionsId == 0 || _optionsId == '') {
        this.setData({
          popupSpecs2: false
        });
      } else {
        this.setData({
          popupSpecs: false
        });
      }
      wx.navigateTo({
        url: url + submitActionTag + "&goodsId=" + _goodsId + "&optionsId=" + _optionsId + "&total=" + _total + "&activity_id=" + activity_id,
      });
    },
    // 设置 珍惠拼 拼团层级的选择状态 过滤数据
    setZhpGroupInfo(_id) {
      // let that = this;
      if(this.data.gooddatas && this.data.gooddatas.has_many_options){
        for (let i = 0; i < this.data.gooddatas.has_many_options.length; i++) {
          let _optionSpecs = this.data.gooddatas.has_many_options[i].option_id;
          if (_optionSpecs == this.data.optionsId) {
            this.data.optionsMaxCount = this.data.gooddatas.has_many_options[i].buy_limit == 0 ? this.data.gooddatas.has_many_options[0].stock : this.data.gooddatas.has_many_options[0].buy_limit; // 当前组合的购买限制数, 为0 时为无限制购买
            this.setData({
              popStock: this.data.gooddatas.has_many_options[i].stock,
              popPrice: this.data.gooddatas.has_many_options[i].group_price
            });
          }
        }
      }
    }
  },
});